"use strict";
uk.states.menu = {
	btnstart:null,
	preload: function(){
		uk.gui.show_tip_message(null);
		uk.localdata.loginname = localStorage.getItem('loginname');
		uk.localdata.visitor = localStorage.getItem('visitor') == 'true';
	},
	
	create: function(){
		this.bg = this.game.add.sprite(0,0,'menubg');
		this.bg.width = this.stage.width;
		this.bg.height = this.stage.height;
		this.btnstart = this.game.add.button(0,0,'btn_start',this.on_click_start,this,1,0);
		this.btnstart.alignIn(this.bg,Phaser.CENTER,0,0);
	},
	
	shutdown:function(){
		uk.netunbind(this);
	},

	on_click_start:function(){
		this.btnstart.visible = false;
		uk.connect(function(success){
			this.btnstart.frame = 0;
			this.btnstart.visible = !success;
			if(success){
				if(uk.logic.self != null){
					uk.game.state.start('main');
				}else if(uk.localdata.loginname && uk.localdata.visitor){
					/**只有游客才使用这个。。。 */
					console.log('visitor login:',uk.localdata.loginname,uk.localdata.visitor);
					uk.netsend(uk.netevents.LOGIN,{name:uk.localdata.loginname,pass:''});
					uk.netbind(uk.netevents.LOGIN,this.on_login,this);
				}else{/**重新产生个游客 */
					uk.localdata.visitor = true;
					uk.netbind(uk.netevents.LOGIN,this.on_login,this);
					uk.netsend(uk.netevents.VISITORLOGIN,{});
				}
			}
		},this);
	},

	on_login:function(obj){
		console.log('login result',obj);
		if(!obj.success){
			uk.localdata.loginname='';
			uk.localdata.visitor = false;
			localStorage.setItem('loginname',uk.localdata.loginname);
			localStorage.setItem('visitor',uk.localdata.visitor);
			this.btnstart.visible = true;
			return;
		}
		if(uk.localdata.visitor){
			localStorage.setItem('loginname',obj.info.id);
			localStorage.setItem('visitor',uk.localdata.visitor);
		}else{
			localStorage.setItem('loginname',obj.info.id);
			localStorage.setItem('visitor',false);
		}
	}
};